import { createRouter, createWebHashHistory } from 'vue-router'
import NProgress from 'nprogress'
import { useAuthStore } from '../stores/auth'
import cfg from '@/config/config'
import routes from './router'

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach(async (to, from) => {
  NProgress.start()
  const store = useAuthStore()

  if (store.isLoggedIn) {
    if (to.name === 'login') {
      return { name: 'home' }
    } else {
      return true
    }
  } else {
    console.log(to)
    if (cfg.WhiteList.indexOf(to.name) > -1) {
      return true
    } else {
      return { name: 'login', query: { redirect: to.fullPath } }
    }
  }
})

router.afterEach((to, from) => {
  NProgress.done()
})

export default router
